package server.model.commentModel;

import org.apache.commons.dbutils.handlers.BeanListHandler;
import server.db.DBDriver;
import server.db.DBFactory;
import server.entity.Comment;
import server.util.InfoUtils.Info;
import server.util.InfoUtils.InfoEnum;
import server.util.InfoUtils.InfoUtil;
import server.util.MyUtils;

import java.util.ArrayList;
import java.util.List;

public class CommentModel {
    //添加评论
    public Info addComment(Comment m) {
        String sql = "insert into comment (last_comment_id,good_id,user_id,message,date) values (?,?,?,?,now())";
        //判空
        if (!MyUtils.NOTNULL(m.getLastCommentId(), m.getGoodId(), m.getUserId(), m.getMessage())) {
            return InfoUtil.getInfo(InfoEnum.PARAMS_NULL);
        }

        ArrayList<Object> params = new ArrayList<>();
        params.add(m.getLastCommentId());
        params.add(m.getGoodId());
        params.add(m.getUserId());
        params.add(m.getMessage());

        int line = DBFactory.getDBDriver().update(sql, params.toArray());
        if (line > 0) {
            return InfoUtil.getInfo(InfoEnum.SUCCESS);
        } else {
            return InfoUtil.getInfo(InfoEnum.FAIL);
        }
    }


    //通过goodId获取评论
    public Info getCommentByGoodId(Integer goodId) {
        String sql = "select * from comment where good_id = ? order by date desc";
        if (!MyUtils.NOTNULL(goodId)) {
            return InfoUtil.getInfo(InfoEnum.PARAMS_NULL);
        }
        List<Comment> comments = DBFactory.getDBDriver().query(sql, new BeanListHandler<>(Comment.class, DBDriver.getProcess()), goodId);
        if (comments == null) {
            return InfoUtil.getInfo(InfoEnum.FAIL);
        } else if (comments.size() == 0) {
            return InfoUtil.getInfo(1, "该商品没有评论");
        } else {
            return InfoUtil.getInfo(comments);
        }
    }
}
